<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use app\common\model\MemberMiniappAudit;
use app\common\model\MemberMiniappOrder;
use buwang\exception\MiniappException;
use buwang\facade\WechatProgram;
use app\common\model\MemberPayment;
use app\common\model\MemberMiniapp;
use buwang\base\MemberBaseController;
use think\facade\Db;
use think\facade\View;

class Setting extends MemberBaseController
{
    public function initialize()
    {
        parent::initialize();

        if ($this->user->lock_config) {
            throw new MiniappException('你账户锁定配置权限',403);
        }
        if ($this->user->parent_id) {
            throw new MiniappException('仅创始人有权限访问',403);
        }
        if (!$this->member_miniapp_id) {
            throw new MiniappException('未找到所属应用,请先开通应用',403);
        }
        //$this->assign('pathMaps', [['name'=>$this->member_miniapp->appname,'url'=>'javascript:;'],['name'=>'应用管理','url'=>url("system/passport.setting/index")]]);
        $this->model = new MemberMiniapp();
    }

    public function index()
    {
        self::isMemberAppAuth();
        //日期
        $date = date('Y-m-d', time());
        //站点名称
        $web_name = bw_config('web_config.web_name');
        //微信支付信息
        $wechat = [];
        $wechat_payment = MemberPayment::where(['apiname' => 'wechat', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
        if ($wechat_payment) $wechat = json_decode($wechat_payment['config'], true);
        //支付宝支付信息
        $alipay = [];
        $alipay_payment = MemberPayment::where(['apiname' => 'alipay', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
        if ($alipay_payment) $alipay = json_decode($alipay_payment['config'], true);

        //开放平台授权验证url https://mall.buwangkeji.com/api/wechat_auth/$APPID$/server
        $APPID = $this->member_miniapp['mp_appid'] ?:'$APPID$';
        $navbar_url = "{$this->request->domain()}/api/wechat_auth/{$APPID}/server";

        /**
         * 开放平台小程序管理
         * is_commit = 1、2、3、4
         * 1、基础信息设置 2、上传代码 3、提交审核 4、发布小程序
         */
        $view['is_authorize'] = 0;//标识已经认证授权过小程序
        $view['audit']['is_commit'] = 1;
        $view['audit']['state'] = 0;//没有查询到小程序提交记录(还没有进行过提交)
        if ($this->member_miniapp->miniapp->is_openapp && $this->member_miniapp->miniapp_appid) {//是开放平台并且有appid(已经授权)
            $miniapp = WechatProgram::isTypes($this->member_miniapp_id);//获取小程序开放平台操作实例
            if ($miniapp) {
               $view['is_authorize'] = 1;
                $view['auditid']['status'] = -1;
                $audit = MemberMiniappAudit::where(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id])->find(); //查询状态
                if ($audit) {
                    $view['audit'] = $audit;
                    //已经提交审核，查询审核状态 is_commit = 3 && state = 1
                    if ($view['audit']['is_commit'] == 3 && $view['audit']['state'] == 1) {
                        $rel = $miniapp->code->getLatestAuditStatus();//查询最新一次提交的审核状态
                        if ($rel['errcode'] == 0) {
                            $view['auditid'] = $rel;
                            if ($rel['status'] == 1) {//1审核被拒绝 0审核成功2审核中3已撤回
                                $view['audit']->state = 0;
                                $view['audit']->is_commit = 2;//重新上传
                                $view['audit']->save();
                            }
                        }
                    }
                    //已发布的代码 is_commit = 4 && state = 0
                    $view['update_var'] = 0;
                    if ($view['audit']['is_commit'] == 4 && $view['audit']['state'] == 0) {
                        //$var = MemberMiniappOrder::where(['id' => $this->member_miniapp->miniapp_order_id])->field('update_var')->find();
                        if ($this->member_miniapp->miniapp->template_id > $this->member_miniapp->template_id) {//有新版本 重新上传小程序代码
                            $view['update_var'] = 1;
                            $view['audit']['is_commit'] = 2;
                        }
                    }
                    if (!file_exists(public_path() . $view['audit']['trial_qrcode'])) {
                        $view['audit']['trial_qrcode'] = '';
                    }
                } else {
                    $view['audit']['state'] = 0;//没有查询到小程序提交记录(还没有进行过提交)
                }
            }
        }
        View::assign($view);
        View::assign('date', $date);
        View::assign('update_var', $view['update_var']??0);
        View::assign('web_name', $web_name);
        View::assign('navbar_url', $navbar_url);
        View::assign('wechat', $wechat);
        View::assign('alipay', $alipay);
        return view();
//
//
//        //保存后的应用配置表单数据
//        $apply =array();
//        //$apply['appname']= 12312312312;
//
//        //保存后的微信支付表单数据
//        $pay =array();
//        //$pay['key']= 12312312312;
//        return view('',['entity' => $apply,'entity_pay' => $pay]);
    }

    /**
     * 编辑
     * @menu true
     * @param int $id
     */
    public function edit($id = 0)
    {
        $row = $this->model->find($id);

        if (request()->isPost()) {
            if (!$row) return $this->error('记录不存在');

            $param = request()->post();
            //TODO 参数验证

            $this->model->startTrans();
            try {
                //TODO 更新记录
                $row->save($param);
                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error('编辑失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('编辑成功');
        }

        if (!$row) return $this->error_jump('记录不存在');

        View::assign('row', $row);
        return view();
    }

    public function wechat()
    {
        if (request()->isPost()) {
            $param = request()->post();

            $data = [
                'apiname' => 'wechat',
                'member_id' => $this->uid,
                'member_miniapp_id' => $this->member_miniapp['id'],
                'config' => json_encode($param)
            ];

            $wechat_payment = MemberPayment::where(['apiname' => 'wechat', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
            if ($wechat_payment) $memberPayment = $wechat_payment;
            else $memberPayment = new MemberPayment();

            Db::startTrans();
            try {
                //TODO 更新记录
                $memberPayment->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error('修改失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('修改成功');
        }
    }

    public function alipay()
    {
        if (request()->isPost()) {
            $param = request()->post();

            $data = [
                'apiname' => 'alipay',
                'member_id' => $this->uid,
                'member_miniapp_id' => $this->member_miniapp['id'],
                'config' => json_encode($param)
            ];

            $wechat_payment = MemberPayment::where(['apiname' => 'alipay', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
            if ($wechat_payment) $memberPayment = $wechat_payment;
            else $memberPayment = new MemberPayment();

            Db::startTrans();
            try {
                //TODO 更新记录
                $memberPayment->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error('修改失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('修改成功');
        }
    }


}
